import sys                        
import pygame                     
from pygame.locals import * #constants from pygame.locals - like OPENGL, K_1, etc...
from OpenGL.GL import * # This is so we can just do glXXXX() instead of OpenGL.GL.glXXXXX()
from random import randint
import numpy as np
import math

RESOLUTION = (800,600)

class palette:
	@staticmethod
	def white():
		glColor(1.0,1.0,1.0)
	@staticmethod
	def green():
		glColor(0.0,1.0,0.0)
	@staticmethod
	def red():
		glColor(1.0,0.0,0.0)

SIZE = 4
SX = RESOLUTION[0]/SIZE
SY = RESOLUTION[1]/SIZE
cellcount = 0

pause = True

field = np.zeros((SX,SY),dtype=int)
field[SX/2,SY/2] = 1

def rectangle(x,y,sx,sy):
	glVertex(x,y,0)
	glVertex(x+sx,y,0)
	glVertex(x+sx,y+sy,0)
	glVertex(x,y+sy,0)

def addcell():
	global field,cellcount
	alpha = randint(0,360)*math.pi/180
	x = SX/2.0 - math.sin(alpha)* SY/2.1
	y = SY/2.0 - math.cos(alpha)* SY/2.1
	alpha = randint(0,360)*math.pi/180
	dx = math.sin(alpha)/2
	dy = math.cos(alpha)/2
	while True:
		x += dx
		y += dy
		if x<0 or x>=SX or y<0 or y>=SY:
			return False
		if field[int(x),int(y)]:
			field[int(x-dx),int(y-dy)] = 1
			palette.green()
			rectangle(int(x)*SIZE,int(y)*SIZE,SIZE-1,SIZE-1)
			palette.red()
			rectangle(int(x-dx)*SIZE,int(y-dy)*SIZE,SIZE,SIZE)
			cellcount+=1
			return True
	return False


def draw ():
	#glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
	if pause: 
		return
	glBegin(GL_QUADS)                         # Tell OpenGL that we will draw quads
	'''
	for y in xrange(SY):
		for x in xrange(SX):
			if field[x,y]==1:
				rectangle(x*SIZE,y*SIZE,SIZE,SIZE)
	'''
	i=0
	while not addcell():
		i+=1
		if i>10:
			break
	glEnd()

	glFlush()                                # Flush everything to screen ASAP
	pygame.display.flip()                    # Flip the double-buffer

pygame.init()  # kickstart pygame

# we want a fullscreen, 1280x1024, SDL surface that supports doublebuffered OpenGL
pygame.display.set_mode(RESOLUTION,OPENGL|DOUBLEBUF)



glMatrixMode(GL_PROJECTION)             # Select GL_PROJECTION matrix
glLoadIdentity()                        # Reset GL_PROJECTION matrix
glOrtho (0,RESOLUTION[0],0,RESOLUTION[1],-1,1)            # Set up orthographic projection

glClearColor(0.0,0.0,0.0,0.0)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

draw()                                  # Call draw function


while 1:
	event=pygame.event.poll ()

	if event.type is QUIT:
		sys.exit(0)

	draw()

	if event.type is KEYDOWN:
		if event.key is K_ESCAPE:
			sys.exit(0)
		if event.key is K_SPACE:
			pause = not pause
